<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Title</title>
	<script src="js/vue-2.6.12.js"></script>
	<link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
	<script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>
	<script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
	<style type="text/css">
      .table>thead>tr>th { text-align: center;}
	</style>
</head>
<body>

<div id="app">
	<div class="container" >
		
		<div v-if="books.length > 0">
			<table class="table table-striped text-center">
				<thead>
				<tr>
					<th>编号</th>
					<th>书籍名称</th>
					<th>出版日期</th>
					<th>价格</th>
					<th>购买数量</th>
					<th>操作</th>
				</tr>
				</thead>
				<tbody>
				
				<tr v-for="(book,index) in books">
					<!--这里使用 index 作为编号 即使删除某项 编号也是连续的-->
					<td>{{index+1}}</td>
					<td>{{book.name}}</td>
					<td>{{book.date}}</td>
					<!--    价格显示 使用函数的方式-->
					<!--    <td>{{getFinalPrice(book.price)}}</td>-->
					<!--    使用过滤器的方式-->
					<td>{{book.price }}</td>
					
					<td>
						<button @click="btn_reduce(index)">-</button>
						{{book.count}}
						<button @click="btn_increase(index)">+</button>
					</td>
					<td><button @click="btn_delete(index)">移除</button></td>
				</tr>
				
				<tr>
					<td>总价</td>
					<td>{{totalPrice}}</td>
				</tr>
				
				</tbody>
			</table>
		</div>
		
		<div v-else>
			<h2>购物车为空</h2>
		</div>
	<hr>
	<hr>
		
		<h3>添加book</h3>
		<span>书名&nbsp;&nbsp;&nbsp;&nbsp;</span> <input type="text" v-model="newBook.name"> <br>
		<span>出版时间</span> <input type="text" v-model="newBook.date"> <span>(xxxx-xx) 年-月</span><br>
		<span>价格&nbsp;&nbsp;&nbsp;&nbsp;</span> <input type="text" v-model="newBook.price"><br>
		<span>数量&nbsp;&nbsp;&nbsp;&nbsp;</span> <input type="text" v-model="newBook.count"><br>

		
		<button type="button" @click="addBook">添加</button>
		
	</div>

	
	
	
</div>


<script>
	
	let app = new Vue({
	  el:"#app",
	  data:{
	    
	    newBook:{
	      name:"",
	      date:"",
	      price:"",
	      count:"",
	    },
	    
	    books:[
	      {
	        name:"JAVA编程基础",
	        date:"2008-09",
	        price:39.00,
	        count:2
	      }
	    ]
	    
	  },
	  methods:{
        btn_reduce(index){
          if (this.books[index].count>1){
            this.books[index].count--;
          }
        },
        btn_increase(index){
          this.books[index].count++;
        },
        btn_delete(index){
          this.books.splice(index,1);
        },
	    addBook(){
            let newBook = JSON.parse(JSON.stringify(this.newBook));
            this.books.push(newBook);
            this.newBook={};
	    }
	  },
	  computed:{
	    totalPrice() {
	      return this.books.reduce(function (preValue,book) {
	        return preValue+book.price*book.count;
          },0);
        }
      }
	})
	
</script>

</body>
</html>